//var single_name_old;
var mutex_input_dblclick = 0;
//element-global
$(function(){
    function show_revise_change(that){
        $(that).children(".row-hover").hide();
        $(that).children(".control-sub").show();
        return true;
    };

    $(".row-hover .controls-text-small").live("dblclick",function(){
        /*
        if(mutex_input_dblclick) return;
        else mutex_input_dblclick=1;

        show_revise_change($(this).parent().parent().parent());
        */
        $(this).parent().parent().children(".span1-compact").children().children(".icon-edit").trigger("click");
    });

    $(".row-hover .icon-edit").live("click",function(){
        if(mutex_input_dblclick) return;
        else mutex_input_dblclick=1;

        show_revise_change($(this).parent().parent().parent().parent());
        //当修改属性时
        statusArray['attribute'] = $(this).parent().parent().parent().parent().parent().parent().parent().children("input[type='hidden']").val();
        statusArray['attributeElem'] =chToEn[$(this).parent().parent().parent().children(".span4").children("label").text()];
    });

    $(".icd-element-input-cancel").live("click",function(){
        var single_name_old = $(this).parent().parent().parent().parent().children(".row").children(".span4").children("p").text();
        if(single_name_old.replace( /^[" "|"　"]*/, "") === '') return;//去除所有均为空的情况
        $(this).parent().parent().children("input[type='text']").val(single_name_old);

        $(this).parent().parent().parent().hide();
        $(this).parent().parent().parent().parent().children(".row").show();
        mutex_input_dblclick = 0;
    });

    $(".icd-element-textarea").live("dblclick",function(){
        if(mutex_input_dblclick) return;
        else mutex_input_dblclick=1;

        $(this).hide();
        $(this).parent().children(".controls-small").show();
    });
});


//submit
$(function(){
    //cdName
    $(".icd-element-input-cd-submit").live("click",function(){
        var value = revise_show_change_submit($(this),icd['cd'],false);
        if(value.state === true){
            var head= '<i class="icon-chevron-right" title="点击叉号删除"></i><i class="icon-remove-sign-right"></i>';
            //替换显示
            $(".bs-docs-sidenav .active").children("a").html(head+value.new);
            $(".bs-docs-sidenav .active").attr('name',value.new);
            $.ajax({
                url: '/post/data/icd-element',
                type: 'post',
                data: {
                    statusArray:statusArray,
                    type : 'cd',
                    process : 'revise',
                    data: {
                        old:value.old,
                        sub :icd['cd'][value.old],
                        new:value.new
                    }
                },
                dataType: 'json',
                success: function(doc){
                    icd = doc.icd;
                    getSourceNav();
                    if(doc.count != 1) return alert("操作失败，请刷新页面后重新尝试");
                }
            });
        }
    });
    //cd _discription
    $(".icd-element-textarea-submit").live("click",function(){
        var newDescription = $(this).parent().parent().children("textarea").val();
        //if(old === '') return;
        if(newDescription.replace( /^[" "|"　"]*/, "") === '') return;//去除所有均为空的情况
        $(this).parent().parent().parent().children("p").text(newDescription);

        $(this).parent().parent().hide();
        $(this).parent().parent().parent().children(".icd-element-textarea").show();
        mutex_input_dblclick = 0;
        $.ajax({
            url: '/post/data/icd-element',
            type: 'post',
            data: {
                statusArray:statusArray,
                type : '_description',
                process : 'revise',
                data: {
                    sub:newDescription
                }
            },
            dataType: 'json',
            success: function(doc){
                if(doc.count != 1) return alert("操作失败，请刷新页面后重新尝试");
                icd = doc.icd;
                getSourceNav();
            }
        });
    });

    $(".icd-element-textarea-cancel").live("click",function(){
        var old = $(this).parent().parent().parent().children("p").text();
        if(old.replace( /^[" "|"　"]*/, "") === '') return;//去除所有均为空的情况
        $(this).parent().parent().children("textarea").val(old);

        $(this).parent().parent().hide();
        $(this).parent().parent().parent().children(".icd-element-textarea").show();
        mutex_input_dblclick = 0;
    });
    //class
    $(".icd-element-input-class-submit").live("click",function(){
        var value = revise_show_change_submit($(this),icd['class'],true);
        if(value.state === true){
            var head= '<i class="icon-chevron-right" title="点击叉号删除"></i><i class="icon-remove-sign-right"></i>';
            $(".bs-docs-sidenav .active").children("a").html(head+value.new);

            $.ajax({
                url: '/post/data/icd-element',
                type: 'post',
                data: {
                    statusArray:statusArray,
                    type : 'classValue',
                    process : 'revise',
                    data: {
                        old:value.old,
                        sub :icd['class'][statusArray['class']]['_value'][value.old],
                        new:value.new
                    }
                },
                dataType: 'json',
                success: function(doc){
                    icd = doc.icd;
                    getSourceNav();
                    if(doc.count != 1) return alert("操作失败，请刷新页面后重新尝试");
                }
            });
        }
    });

    $(".icd-element-input-relation-submit").live("click",function(){
        var class1 = $(this).parent().parent().children().eq(0).children("input[type='text']").val();
        var class2 = $(this).parent().parent().children().eq(1).children("input[type='text']").val();

        if(class1.replace( /^[" "|"　"]*/, "") === '') return;//去除所有均为空的情况
        if(class2.replace( /^[" "|"　"]*/, "") === '') return;//去除所有均为空的情况

        var relationname = class1 +'-'+class2;
        if(checkExist(icd['relation'],relationname)) return alert("名称已存在");

        var text = $(this).parent().parent().parent().children(".row").children(".span4").children("p");
        var oldName=$(text).text();
        $(text).text(relationname);

        $(this).parent().parent().parent().children().show();
        $(this).parent().parent().hide();
        mutex_input_dblclick = 0;

        var head= '<i class="icon-chevron-right" title="点击叉号删除"></i><i class="icon-remove-sign-right"></i>';
        $(".bs-docs-sidenav .active").children("a").html(head+relationname);

        $.ajax({
            url: '/post/data/icd-element',
            type: 'post',
            data: {
                statusArray:statusArray,
                type : 'relation',
                process : 'revise',
                data: {
                    old:oldName,
                    sub :icd['relation'][statusArray['relation']]['_value'][oldName],
                    new:relationname
                }
            },
            dataType: 'json',
            async: true,
            success: function(doc){
                icd = doc.icd;
                getSourceNav();
                if(doc.count != 1) return alert("操作失败，请刷新页面后重新尝试");
            }
        });
    });

    $(".icd-element-input-relation-cancel").live("click",function(){
        var relationname = $(this).parent().parent().parent().children(".row").children(".span4").children("p").text();
        relationname = relationname.split("-");
        if(relationname[0].replace( /^[" "|"　"]*/, "") === '') return;//去除所有均为空的情况
        if(relationname[1].replace( /^[" "|"　"]*/, "") === '') return;//去除所有均为空的情况

        $(this).parent().parent().children().eq(0).children("input[type='text']").val(relationname[0]);
        $(this).parent().parent().children().eq(1).children("input[type='text']").val(relationname[1]);

        $(this).parent().parent().parent().children().show();
        $(this).parent().parent().hide();
        mutex_input_dblclick = 0;
    });

    function revise_show_change_submit(that,dir,checkLegal){
        var value = {state:false};
        value.new = $(that).parent().parent().children("input[type='text']").val();

        if(value.new.replace( /^[" "|"　"]*/, "") === '') return value;//去除所有均为空的情况
        else if(checkLegal){
            if(checkExist(dir,value.new)) return alert("名称已存在");
        }
        value.state = true;

        var text = $(that).parent().parent().parent().parent().children(".row").children(".span4").children("p");
        value.old = $(text).text();
        $(text).text(value.new);

        $(that).parent().parent().parent().hide();
        $(that).parent().parent().parent().parent().children(".row").show();

        mutex_input_dblclick = 0;
        return value;
    };

    function checkExist(dir,name){
        if(dir[name] != undefined) return true;
        for(var elem in dir){
            if(dir[elem]["_value"][name] != undefined) return true;
        }
        return false;
    };

    $(".icd-element-input-submit").live("click",function(){
        //var attributeName = $(this).parent().parent().parent().parent().parent().children().eq(0).find("p").text();
        var attributeName = $(this).parent().parent().parent().parent().parent().parent().parent().children("input[type='hidden']").val();
        statusArray['attribute']=attributeName;
        //alert("attribute:"+statusArray['attribute']);
        var label = $(this).parent().parent().parent().children("label").text();
        var labelEn = chToEn[label];
        var value = revise_show_change_submit($(this),null,false);
        //var that = $(this).parent().parent().parent().parent().parent().parent().parent();
        var that = $(this).parent().parent().parent().parent();

        //无需做重复性检验这里只是为了统一
        statusArray['attributeElem']=labelEn;

        if(value.state === true){
            if(label === "名称"){
                $.ajax({
                    url: '/post/data/icd-element',
                    type: 'post',
                    data: {
                        statusArray:statusArray,
                        type : 'attributeValue',
                        process : 'revise',
                        data: {
                            old:value.old,
                            sub :icd['class'][statusArray['class']][statusArray['attribute']]['_value'][value.old],
                            new:value.new
                        }
                    },
                    dataType: 'json',
                    async: true,
                    success: function(doc){
                        icd = doc.icd;
                        getSourceNav();
                        if(doc.count != 1) return alert("操作失败，请刷新页面后重新尝试");
                        summaryIntoString($(that).parent().parent().parent());
                        $(that).children(".recommend-element").trigger("click");
                    }
                });
            }else{
                var sub = icd['class'][statusArray['class']][statusArray['attribute']][labelEn][value.old];
                if(value.old==="") {alert("1"); sub={_nor:1}};
                $.ajax({
                    url: '/post/data/icd-element',
                    type: 'post',
                    data: {
                        statusArray:statusArray,
                        type : 'attributeElemValue',
                        process : 'revise',
                        data: {
                            old:value.old,
                            sub :sub,
                            new:value.new
                        }
                    },
                    dataType: 'json',
                    async: true,
                    success: function(doc){
                        icd = doc.icd;
                        getSourceNav();
                        if(doc.count != 1) return alert("操作失败，请刷新页面后重新尝试");
                        summaryIntoString($(that).parent().parent().parent());
                        $(that).children(".recommend-element").trigger("click");
                    }
                });
            }
        }
    });

    $(".icd-element-input-relation-type-submit").live("click",function(){
        var value={};
        value.new = $(this).parent().parent().children("label").children("input[type='radio']:checked").val();
        var text = $(this).parent().parent().parent().children(".row").children(".span4").children("p");
        value.old = $(text).text();
        $(text).text(value.new);

        value.new = chToEn[value.new];
        value.old = chToEn[value.old];

        $(this).parent().parent().hide();
        $(this).parent().parent().parent().children(".row").show();
        mutex_input_dblclick=0;
        var url='/post/html/icd-element-relation-sub-'+value.new;

        $.ajax({
            url: '/post/data/icd-element',
            type: 'post',
            data: {
                statusArray:statusArray,
                type : 'relationType',
                process : 'revise',
                data: {
                    old:value.old,
                    sub :icd['relation'][statusArray['relation']][value.old],
                    new:value.new
                }
            },
            dataType: 'json',
            async: true,
            success: function(doc){
                icd = doc.icd;
                getSourceNav();
                if(doc.count != 1) return alert("操作失败，请刷新页面后重新尝试");
                $.ajax({
                    url: url,
                    type: 'post',
                    data: {},
                    success: function(html){
                        $("#icd-relation-detail").children().remove();
                        $("#icd-relation-detail").append(html);
                        var className = statusArray['relation'].split("-");
                        icd_element_relationType_show[value.new]($("#icd-relation-detail"),className,icd['relation'][statusArray['relation']][value.new]);
                    }
                });
            }
        });
    });

    $(".icd-element-input-relation-type-cancel").live("click",function(){
        var checked_val = $(this).parent().parent().parent().find("p").text();
        $(this).parent().parent().children("label").children("input[type='radio'][value="+checked_val+"]").attr('checked','checked');

        $(this).parent().parent().hide();
        $(this).parent().parent().parent().children(".row").show();
        mutex_input_dblclick=0;
    });

    $(".icd-element-input-multi1-submit").live("click",function(){
        multi_submit($(this),'multiply1');
    });

    $(".icd-element-input-multi2-submit").live("click",function(){
        multi_submit($(this),'multiply2');
    });

    multi_submit = function(that,multiType){
        var value = revise_show_change_submit($(that),null,false);
        statusArray['relationElem'] = multiType;
        if(value.state === true){
            $.ajax({
                url: '/post/data/icd-element',
                type: 'post',
                data: {
                    statusArray:statusArray,
                    type : 'relationElemValue',
                    process : 'revise',
                    data: {
                        old:value.old,
                        sub :icd['relation'][statusArray['relation']][statusArray['relationType']][multiType][value.old],
                        new:value.new
                    }
                },
                dataType: 'json',
                success: function(doc){
                    icd = doc.icd;
                    getSourceNav();
                    if(doc.count != 1) return alert("操作失败，请刷新页面后重新尝试");
                }
            });
        }
    };
});

//accordion-group top lable
$(function(){
    var this_group = '';
    var alert_type = '';
    var alert_name = '';

    $(".accordion-heading .span4").live("click",function(){
        //$(this).parent().parent().parent().parent().children(".accordion-body").toggle();
        $(this).parent().children(".span1-compact").children().children(".icon-zoom-in").trigger("click");
    });

    $(".accordion-heading .icon-zoom-in").live("click",function(){
        $(this).parent().parent().parent().parent().parent().parent().children(".accordion-body").toggle();
    });

    $(".accordion-heading .icon-trash").live("click",function(){
        this_group = $(this).parent().parent().parent().parent().parent().parent();
        var span4 =  $(this_group).children(".accordion-heading").children().children().children(".span4");
        alert_type = $(span4).children("label").text();
        alert_name = $(span4).children("p").text();

        $('#modal-alert-element').modal('show');
    });

    $('#modal-alert-element').on('show', function () {
        $("#modal-alert-element").children(".modal-body").children("h5").text("确定删除  "+alert_type+":"+alert_name+"?");
    });

    $('#delete-element').live('click',function(){
        var status_type;
        var attribute;
        if(alert_type === '属性'){
            status_type = 'attribute';
            attribute = $(this_group).children("input[type='hidden']").val();
            statusArray['attribute']= attribute;
            alert_name = attribute;
            var sub = icd['class'][statusArray['class']][alert_name];
        }else{
            status_type = 'attributeElem';
            attribute = $(this_group).parent().parent().parent().children("input[type='hidden']").val();
            statusArray['attribute']= attribute;
            statusArray['attributeElem']=chToEn[alert_type];
            alert_name = chToEn[alert_type];
            var sub = icd['class'][statusArray['class']][attribute][alert_name];
        }
        $(this_group).remove();
        $.ajax({
            url: '/post/data/icd-element',
            type: 'post',
            data: {
                statusArray:statusArray,
                type : status_type,
                process : 'remove',
                data: {
                    new:alert_name,
                    sub:sub
                }
            },
            dataType: 'json',
            async: true,
            success: function(doc){
                icd =doc.icd;
                getSourceNav();
                if(doc.count != 1) return alert("创建失败，请刷新页面后重新尝试");
                else $(p_delete_item).remove();
            }
        });
    });

    $(".accordion-heading .icon-plus-sign").live("click",function(){
        this_group = $(this).parent().parent().parent().parent().parent().parent();
        statusArray['attribute'] = $(this_group).children("input[type='hidden']").val();
        var span4 =  $(this_group).children(".accordion-heading").children().children().children(".span4");
        alert_type = $(span4).children("lable").text();
        alert_name = $(span4).children("p").text();
        $('#modal-attribute-add').modal('show');
    });

    $('#modal-attribute-add').on('show', function () {
        $("#modal-attribute-add").children(".modal-body").children(".btn-group").children("button").html('选择类型 <span class="caret"></span>');
        var ul = $("#modal-attribute-add").children(".modal-body").children(".btn-group").children("ul");
        $(ul).children().remove();
        var dir = icd['class'][statusArray['class']][statusArray['attribute']];

        for(var i=0;i<m_attributeElem.length;i++){
            if(dir[m_attributeElem[i]] === undefined){
                $(ul).append("<li value="+m_attributeElem[i]+"><a href='javascript:;'>"+enToCh[m_attributeElem[i]]+"</a></li>");
            }
        }
    });

    $("#attribute-add").live("click", function(){
        var attributeElem = $(this).parent().parent().parent().children(".modal-body").children(".btn-group").children("button").text();
        attributeElem = chToEn[attributeElem];
        if(attributeElem === undefined) return alert("创建失败，为选择类型");
        var attributeElemValue = $(this).parent().parent().parent().children(".modal-body").children("input[type='text']").val();
        statusArray['attributeElem']=attributeElem;
        $.ajax({
            url: '/post/data/icd-element',
            type: 'post',
            data: {
                statusArray:statusArray,
                type : 'attributeElemValue',
                process : 'add',
                data: {
                    new:attributeElemValue
                }
            },
            dataType: 'json',
            async: true,
            success: function(doc){
                icd = doc.icd;
                getSourceNav();
                if(doc.count != 1) return alert("操作失败，请刷新页面后重新尝试");
                $.ajax({
                    url: '/post/html/icd-element',
                    type: 'post',
                    data: {},
                    success: function(html)
                    {
                        var root =$(this_group).children(".accordion-body").children(".accordion-inner");
                        $(root).append(html);
                        icd_element_attributeElem_show($(root).children().last(),attributeElem,icd['class'][statusArray['class']][statusArray['attribute']][statusArray['attributeElem']]);
                    }
                });
            }
        });
    });

    $(".btn-group.controls-small li").live("click",function(){
        var this_value = $(this).children("a").text();
        $(this).parent().parent().children("button").html(this_value+'<span class="caret"></span>');
    });

    $(".attribute-plus").live("click",function(){
        this_group = $(this).parent().parent().children(".accordion").children().last();
        $('#modal-create-attribute').modal('show');
    });

    $(".accordion-heading .icon-plus").live("click",function(){
        this_group = $(this).parent().parent().parent().parent().parent().parent();
        $('#modal-create-attribute').modal('show');
    });

    $("#create-attribute").live("click", function(){
        var value = $(this).parent().parent().parent().children(".modal-body").children("input[type='text']").val();
        $.ajax({
            url: '/post/data/icd-element',
            type: 'post',
            data: {
                statusArray:statusArray,
                type : 'attribute',
                process : 'add',
                data: {
                    new:value
                }
            },
            dataType: 'json',
            async: true,
            success: function(doc){
                icd = doc.icd;
                getSourceNav();
                if(doc.count != 1) return alert("操作失败，请刷新页面后重新尝试");
                $.ajax({
                    url: '/post/html/icd-element-attribute',
                    type: 'post',
                    data: {},
                    success: function(html)
                    {
                        $(this_group).after(html);
                        icd_element_attribute_show($(this_group).next(),value,icd['class'][statusArray['class']][value]);
                    }
                });
            }
        });
    });

    $(".accordion-heading .icon-arrow-up").live("click",function(){
        var this_root = $(this).parent().parent().parent().parent().parent().parent();
        var html = '<div class="accordion-group">'+$(this_root).html()+'</div>';
        $(this_root).prev().before(html);
        $(this_root).remove();

    });

    $(".accordion-heading .icon-arrow-down").live("click",function(){
        var this_root = $(this).parent().parent().parent().parent().parent().parent();
        var html = '<div class="accordion-group">'+$(this_root).html()+'</div>';
        $(this_root).next().after(html);
        $(this_root).remove();
    });

    $(".accordion-body .icon-trash").live("click",function(){
        this_group = $(this).parent().parent().parent().parent();
        var span4 =  $(this_group).children(".row").children(".span4");
        alert_type = $(span4).children("label").text();
        alert_name = $(span4).children("p").text();

        $('#modal-alert-element').modal('show');
    });

    $(".icon-refresh.source").live("click",function(){
        var item={};
        item.label = $(this).parent().parent().children("label").text();
        item.value = $(this).parent().parent().children("input").val();

        var ccd_dir;
        var array;
        $("#modal-source-detail").children(".modal-body").children(".detail-info").children().remove();
        switch(item.label){
            case "类":
                ccd_dir = ccd["class"][item.value];
                for(var key in ccd_dir){
                    if(regex.test(key) === false){
                        $("#modal-source-detail").children(".modal-body").children(".detail-info").append(
                            "<label class='control-label-small controls-small'>属性:</label>"
                        +"<p class='controls-text-small' style='padding-left: 75px'>"+key+"</p>")
                    }
                };
                break;
            case "属性":
                ccd_dir = ccd['class'][statusArray['class']][item.value];
                for(var key in ccd_dir){
                    if(regex.test(key) === false){
                        for(var val in ccd_dir[key]){
                            if(regex.test(val) === false){
                                $("#modal-source-detail").children(".modal-body").children(".detail-info").append(
                                    "<label class='control-label-small controls-small'>"+enToCh[key]+":</label>"
                                +"<p class='controls-text-small' style='padding-left: 75px'>"+val+"</p>")
                            }
                        }
                    }
                };
                break;
            default: break;
        }
    });

    $(".icon-ok.source").live("click",function(){
        var item={};
        item.label = $(this).parent().parent().children("label").text();
        item.value = $(this).parent().parent().children("input").val();
        item.exist = false;

        generateItem(item);
        if(item.exist)  return alert("操作失败，源数据已存在！")
        $.ajax({
            url: '/post/data/icd-element',
            type: 'post',
            data: {
                statusArray:statusArray,
                type : item.type,
                process : 'revise',
                data: {
                    old:modalSourceValue,
                    sub :item.sub,
                    new:item.value
                }
            },
            dataType: 'json',
            success: function(doc){
                icd = doc.icd;
                getSourceNav();
                if(doc.count != 1) return alert("操作失败，请刷新页面后重新尝试");
                updateSource(item.label,item.value);
            }
        });
    })

    generateItem = function(item){
        switch(item.label){
            case "类":
                item.type = 'class';
                item.sub = icd['class'][statusArray['class']];
                if(icd['class'][item.value] != undefined) item.exist=true;
                break;
            case "属性":
                item.type = 'attribute';
                item.sub = icd['class'][statusArray['class']][statusArray['attribute']];
                if(icd['class'][statusArray['class']][item.value] != undefined) item.exist=true;
                break;
            default: break;
        }
    }
    updateSource = function(label,value){
        switch(label){
            case "类":
                $(".bs-docs-sidenav .active").attr('name',value);
                $(".bs-docs-sidenav .active").trigger('click');
                break;
            case "属性":
                $(recommenditem).children("input[type='hidden']").val(value);
                $(recommenditem).find(".recommend-attribute").trigger('click');
                break;
            default: break;
        }
    }
});




